<template>
  <div class="app-container">
    <el-form class="multiple-from" :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item prop="plotId" label="选择小区：">
        <el-select v-model="queryParams.plotId" placeholder="请选择"   @change="xiaoquChange" clearable>
          <el-option v-for="dict in xiaoquData" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="buildId" label="选择楼栋：">
        <el-select v-model="queryParams.buildId" placeholder="请选择"  @change="loudonChange" clearable>
          <el-option v-for="dict in loudongData" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="unitId" label="选择单元：">
        <el-select v-model="queryParams.unitId" placeholder="请选择" clearable>
          <el-option v-for="dict in danyuanData" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="houseNumber" label="门牌号：">
        <el-input v-model="queryParams.houseNumber" placeholder="请输入门牌号" clearable />
      </el-form-item>
      <el-form-item prop="alarmType" label="告警类型：">
        <el-select v-model="queryParams.alarmType" placeholder="请选择" clearable>
          <el-option v-for="dict in dict.type.alarm_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="keyword" label="预警分类：">
        <el-select v-model="queryParams.keyword" placeholder="请选择" clearable>
          <el-option v-for="dict in keywordlist" :key="dict" :label="dict" :value="dict" />
        </el-select>
      </el-form-item>
      <el-form-item prop="alarmLevel" label="告警等级：">
        <el-select v-model="queryParams.alarmLevel" placeholder="请选择" clearable>
          <el-option v-for="dict in dict.type.alarm_level" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="status" label="处理状态：">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable>
          <el-option v-for="dict in statusData" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="time" label="日期：">
        <el-date-picker @change="dateChange" v-model="queryParams.time" value-format="yyyy-MM-dd" type="daterange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div style="margin-bottom: 10px;display: flex;justify-content: space-between;">
      <el-col :span="1.5">
        <el-button type="primary" size="mini" icon="el-icon-circle-close" @click="piliangDel">批量删除</el-button>
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['build:build:export']">导出</el-button>
      </el-col>
      <div>
        <el-button type="primary" size="mini" icon="el-icon-search" @click="showSearch = !showSearch"></el-button>
        <el-button type="primary" size="mini" icon="el-icon-refresh-right" @click="getList"></el-button>
      </div>
    </div>

    <el-table v-loading="loading" :data="typeList" @selection-change="handleSelectionChange">
      <el-table-column v-if="selectFlag" type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index"></el-table-column>
      <el-table-column show-overflow-tooltip label="小区名称" align="center" prop="plotName" />
      <el-table-column show-overflow-tooltip label="楼栋" align="center" prop="buildName"></el-table-column>
      <el-table-column show-overflow-tooltip label="单元" align="center" prop="unitName"></el-table-column>
      <el-table-column show-overflow-tooltip label="户号" align="center" prop="houseNumber" />
      <el-table-column show-overflow-tooltip label="告警设备" align="center" prop="equipmentName"></el-table-column>
      <el-table-column show-overflow-tooltip label="设备编号" align="center" prop="equipmentCode"></el-table-column>
      <el-table-column show-overflow-tooltip label="告警类型" align="center" prop="alarmTypeName"></el-table-column>
      <el-table-column show-overflow-tooltip label="告警等级" align="center" prop="alarmLevel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.alarm_level" :value="scope.row.alarmLevel" />
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="告警描述" align="center" prop="remark"></el-table-column>
      <el-table-column show-overflow-tooltip label="告警时间" align="center" prop="createTime"></el-table-column>
      <el-table-column show-overflow-tooltip label="处理时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.status == 0 ? '' : scope.row.updateTime }}
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="处理备注" align="center" prop="handleRemark"></el-table-column>
      <!-- <el-table-column show-overflow-tooltip label="处理状态" align="center">
        <template slot-scope="scope">
          {{ scope.row.status == 0 ? '未处理' : '已处理' }}
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status === '0'" size="mini" type="text"
            @click="huifu(scope.row, true)">处理</el-button>
          <el-button v-if="scope.row.status === '1'" size="mini" type="text"
            @click="huifu(scope.row, false)">查看</el-button>
          <el-button v-if="scope.row.status === '0'" size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog :title="title" :visible.sync="dialogVisible" width="600px" append-to-body>
      <el-form :model="formData" ref="queryForm" size="small" label-width="100px">
        <el-form-item prop="plotId" label="告警设备：">
          <el-input :disabled="true" v-model="formData.equipmentName"></el-input>
        </el-form-item>
        <el-form-item prop="plotId" label="设备编号：">
          <el-input :disabled="true" v-model="formData.equipmentCode"></el-input>
        </el-form-item>
        <el-form-item prop="plotId" label="告警类型：">
          <el-input :disabled="true" v-model="formData.alarmTypeName"></el-input>
        </el-form-item>
        <el-form-item prop="plotId" label="告警等级：">
          <el-select :disabled="true" v-model="formData.alarmLevel" placeholder="请选择" clearable>
            <el-option v-for="dict in dict.type.alarm_level" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="plotId" label="处理状态：">
          <el-select :disabled="flagInfo" v-model="formData.status" placeholder="请选择" clearable>
            <el-option v-for="dict in statusData" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="formData.status == 1" prop="plotId" label="处理时间：">
          <el-date-picker disabled v-model="formData.updateTime" type="datetime" placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="plotId" label="隐藏或推送：">
          <el-select :disabled="flagInfo" v-model="formData.hideOrPush" placeholder="请选择" clearable>
            <el-option v-for="dict in yinData" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>

          <!-- <el-popover placement="bottom" width="300" v-model="visible">
            <span slot="reference" @click="visible = true" v-if="formData.hideOrPush === 0"
              style="margin-left: 10px;color: #0872f3;cursor: pointer;">设置</span>
            <el-form :model="info" :rules="infoRules" ref="infoForm">
              <div class="setTime">
                <el-form-item prop="shichang">
                  <div style="display: flex;align-items: center;">
                    <span style="color: #fff;">告警推送时间间隔</span>
                    <el-input :disabled="flagInfo" type="number" min="0" autofocus v-model="info.pushNum"
                      style="margin: 0 5px;width:60px;color: #000000;"></el-input>
                    <span style="color: #fff;">分钟一次</span>
                  </div>
                </el-form-item>
              </div>
            </el-form>
            <div class="setTimeBtnBox" style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="visible = false; info.pushNum = ''">取消</el-button>
              <el-button type="primary" size="mini" @click="shezhiOk">确定</el-button>
            </div>
          </el-popover> -->

        </el-form-item>
        <el-form-item label="告警描述：">
          <el-input :disabled="true" v-model="formData.remark" type="textarea" style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item label="处理备注：">
          <el-input :disabled="flagInfo" v-model="formData.handleRemark" type="textarea" style="width: 300px;"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateEquipmentAlarmClick">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { warningList } from "@/api/mock"
import data5 from "@/utils/data5.json"
import { listCPlotSelect,listBuildSelect,listBuildUnitSelect } from "@/api/system/utils"
import { listEquipmentAlarm, updateEquipmentAlarm, delEquipmentAlarm, listAlarmSettingSelect } from "@/api/equipmentAlarm/equipmentAlarm"

export default {
  dicts: ['alarm_level','alarm_type'],
  data() {
    return {
      selectFlag: false,
      dialogVisible: false,
      visible: false,
      showSearch: true,
      xiaoquData: [],
      loudongData: [],
      danyuanData: [],
      statusData: [
        { label: '未处理', value: "0" },
        { label: '已处理', value: "1" },
      ],
      total: 0,
      loading: false,
      queryParams: {
        alarmType:null,
        plotId: null,
        buildId:null,//楼栋id
        unitId: null,//单元id
        houseNumber:null,//门牌号
        status: null,
        startTime: null,
        time:null,
        endTime: null,
        pageNum: 1,
        pageSize: 10,
      },
      keywordlist:[
        "通讯异常",
        "回温异常",
        "供温异常",
        "室温异常",
        "流量异常",
        "开度异常",
      ],
      typeList: [],
      yinData: [
        { label: '隐藏', value: 1 },
        { label: '推送', value: 0 },
      ],
      ids: [],
      title: '告警处理',
      formData: {
        she: '',
        num: '',
        leix: '',
        dengji: '',
        type: '',
        hideOrPush: '',
        miaoshu: '',
        bei: '',
        handleRemark:null
      },
      info: {
        pushNum: ''
      },
      flagInfo: true,
      infoRules: {
        pushNum: [
          { required: true, message: '请输入告警推送时间间隔', trigger: 'blur' },
        ],
      }
    }
  },
  created() {
    listCPlotSelect({}).then(res => {
      this.xiaoquData = res.rows
      this.queryParams.plotId = res.rows[0].value
    }).then(res=>{
    if(this.$route.params.plotId){
      this.getRouterData()
    }
    listBuildSelect({ plotId:this.queryParams.plotId}).then((res) => {
          this.loudongData = res.rows;
        });
      this.getList();
    });
    
    
  },
  methods: {
    handleQuery() {
      this.getList();
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams = {
        alarmType:null,
        plotId: null,
        buildId:null,//楼栋id
        unitId: null,//单元id
        houseNumber:null,//门牌号
        status: null,
        startTime: null,
        time:null,
        endTime: null,
        pageNum: 1,
        pageSize: 10,
      },
      this.getList();
    },

    // 设置时长
    shezhiOk() {
      this.$refs['infoForm'].validate((valid) => {
        console.log(valid);
        this.visible = false
      })
    },
    // 多选框数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      // console.log(this.ids);
    },
    // 处理/查看（flag:true  处理  flag:false  查看）
    huifu(row, flag) {
      this.formData = row
      this.info.pushNum = this.formData.pushNum;
      if (flag) {
        console.log('处理');
        this.flagInfo = false
        this.title = '告警处理'
      }

      if (!flag) {
        console.log('查看');
        this.flagInfo = true
        this.title = '告警查看'
      }
      this.dialogVisible = true
    },
    // 获取列表数据
    getList() {
      this.loading = true;
      listEquipmentAlarm(this.queryParams).then(response => {
        this.typeList = response.rows;
        this.total = response.total;
        this.loading = false;
      }, err => {
        this.loading = false;
      });
    },
    // 更新
    updateEquipmentAlarmClick() {
      this.loading = true;
      this.formData.pushNum = this.info.pushNum;
      if (this.formData.hideOrPush === 1) {
        this.formData.pushNum = 0;
        this.info.pushNum = 0;
      }
      updateEquipmentAlarm(this.formData).then(response => {
        this.$message.success('处理成功')
        this.getList();
        this.loading = false;
        this.dialogVisible = false
      }, err => {
        this.$message.error('处理失败')
      });
    },
    // 批量删除
    piliangDel() {
      const ids = this.ids;
      if (this.ids.length === 0) {
        this.selectFlag = !this.selectFlag
      } else {
        this.$modal.confirm('是否删除所选数据？').then(function () {
          return delEquipmentAlarm(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => { });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除告警？').then(function () {
        return delEquipmentAlarm(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('equipmentAlarm/exportEquipmentAlarm', {
        ...this.queryParams
      }, `告警_${new Date().getTime()}.xlsx`)
    },
    //小区下拉切换
    xiaoquChange(value) {
      if (value) {
        listBuildSelect({ plotId: this.queryParams.plotId }).then((res) => {
          this.queryParams.buildId = null;
          this.queryParams.unitId = null;
          this.loudongData = res.rows;
          this.danyuanData = [];
        });
      } else {
        this.queryParams.buildId = null;
        this.queryParams.unitId = null;
        this.loudongData = [];
        this.danyuanData = [];
      }
    },
    //楼栋下拉切换
    loudonChange(value) {
      if (value) {
        listBuildUnitSelect({ buildId: this.queryParams.buildId }).then((res) => {
          this.queryParams.unitId = null
          this.danyuanData = res.rows
        });
      } else {
        this.queryParams.unitId = null;
        this.danyuanData = [];
      }
    },
    //获取大屏路由参数
    getRouterData(){
      let {name,plotId}= this.$route.params
      console.log(name,plotId);
      if(name==="今日预警"){
        let today = new Date();
        let year = today.getFullYear(); // 获取年份
        let month = today.getMonth() + 1; // 获取月份（0-11，需要加1）
        let day = today.getDate(); // 获取日期
        let formattedDate = year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day);
        console.log(formattedDate); // 输出类似于"2023-11-01"的日期字符串
        this.$set(this.queryParams,"startTime",formattedDate)
        this.$set(this.queryParams,"time",[formattedDate,formattedDate])
        this.$set(this.queryParams,"endTime",formattedDate)
        this.$set(this.queryParams,"plotId",plotId)
        return
      }
      if(name==="预警数量"){
        this.$set(this.queryParams,"plotId",plotId)
        return
      }
      this.$set(this.queryParams,"plotId",plotId)
      this.$set(this.queryParams,"keyword",name)
      
      console.log("大屏参数",this.$route.params);
    },
    //选择日期
    dateChange(e) {
      if (e) {
        this.queryParams.startTime = e[0]
        this.queryParams.endTime = e[1]
      } else {
        this.queryParams.startTime = null
        this.queryParams.endTime = null
      }
    }
  },
}
</script>

<style lang="scss" scoped>
::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}

::v-deep .el-dialog .el-select>.el-input {
  min-width: 200px;
}

::v-deep .el-dialog .el-input>input {
  min-width: 200px;
}

::v-deep input[type='number'] {
  -moz-appearance: textfield !important;
}

::v-deep .setTime {
  .el-form-item .el-form-item__content {
    margin-left: 0px !important;
  }

  .el-input--medium {
    background: #fff;
    border-radius: 4px;
  }

  .el-input>input {
    min-width: 60px;
    width: 60px;
    height: 36px;

    background: #fff !important;
  }
}

::v-deep .setTimeBtnBox {
  margin-top: 10px !important;

  .el-button {
    width: 56px !important;
    height: 28px !important;
    line-height: 28px !important;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 5px !important;
    padding: 0px !important;
    min-width: 56px;

    &:nth-child(1) {
      background: transparent;
    }

    &:nth-child(2) {
      background: #1890ff;
    }
  }


}
</style>
